import type { Directive, DirectiveBinding } from "vue"

const createLoadingElement = (): HTMLElement => {
    let loadingEl = document.createElement('div')
    loadingEl.dataset.role = 'loading'
    loadingEl.className = 'component aloading'
    loadingEl.style.width = '100%'
    loadingEl.style.height = '100%'
    loadingEl.style.position = 'fixed'
    loadingEl.style.top = '0'
    loadingEl.style.left = '0'
    loadingEl.style.zIndex = '1001'
    return loadingEl
}

const queryLoadingElement = (el: HTMLElement): Element | null => {
    return el.querySelector("div[data-role=loading]")
}

const Loading: Directive<any, any> = {
    updated: (el: HTMLElement, binding: DirectiveBinding) => {
        let { value } = binding
        let existEl = queryLoadingElement(el)
        if (value) {
            if (!existEl) {
                let loadingEl = createLoadingElement()
                el.appendChild(loadingEl)
            }
        } else {
            if (existEl) {
                existEl.remove()
            }
        }
    }
}

export default Loading
